﻿using WyUnity.Data.DataAccess;
using WyUnity.Utility;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace WyUnity.Data.Query
{
	public class SqlWhere : Where
	{
		static string PARAM_PATTEN = @"(?<!@)@\w+";
		string _sql;
		object[] _pms;
		public SqlWhere(string nativeSql, params object[] pms)
		{
			_sql = nativeSql;
			_pms = pms;
		}
		public override string ToClip(ParameterProvider pp)
		{
			var ms = Regex.Matches(_sql, PARAM_PATTEN);
			var sql_p = new Dictionary<string, object>();
			foreach (Match m in ms)
			{
				if (!sql_p.ContainsKey(m.Value))
				{
					sql_p.Add(m.Value, null);
				}
			}

			if (sql_p.Count != _pms.Length)
			{
				Log.Get<SqlWhere>().Error("语句要求的参数和实际提供的参数个数不符"
														 + Environment.NewLine + "SQL:" + _sql
														 + Environment.NewLine + "要求参数个数:" + sql_p.Count
														 + Environment.NewLine + "实际参数个数:" + _pms.Length);
				throw new Exception("SQL语句要求的参数和实际提供的参数个数不符");
			}


			var i = 0;
			var sql = _sql;
			foreach (string key in sql_p.Keys)
			{
				var name = pp.CreateOne(_pms[i]);
				sql = sql.Replace(key, name);
				i++;
			}
			return sql;
		}
	}
}
